﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using YWTSSys.Library;
using YWTSSys.Model;
using YWTSSys.DAL;
using System.Data;
using System.Threading;

namespace YWTSSys.BLL
{
    public enum LoginState
    {
        /// <summary>
        /// 登陆成功
        /// </summary>
        success,
        /// <summary>
        /// 用户名或密码错误
        /// </summary>
        inputerror,
        /// <summary>
        /// 登陆失败
        /// </summary>
        other
    }

    public class OUserController:BaseController
    {
        #region 登陆相关
        public static LoginState Login(string UserName, string Pwd,string loginIP)
        {
            bool CreatePersistentCookie = true;
            int UserId = 0;
            //核对用户名密码
            LoginState result = IsAuthenticated(UserName, Pwd, loginIP, ref UserId);

            if (result != LoginState.success)
            {
                return result;
            }
            //处理缓存
            DC.Remove(GetDataCacheKey(LoginOUserInfo, UserId));

            FormsAuthentication.SetAuthCookie(UserId.ToString(), CreatePersistentCookie);
                      

            // FormsAuthentication.

           int PersistentCookieTimeout = 3600 * 24 * 60;
           // int PersistentCookieTimeout = 60;
            if (CreatePersistentCookie == true)
            {
                FormsAuthenticationTicket AuthenticationTicket = new FormsAuthenticationTicket(UserId.ToString(), true, PersistentCookieTimeout);

                string EncryptedAuthTicket = FormsAuthentication.Encrypt(AuthenticationTicket);

                HttpCookie AuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedAuthTicket);

                AuthCookie.Expires = AuthenticationTicket.Expiration;

                AuthCookie.Domain = FormsAuthentication.CookieDomain;

                AuthCookie.Path = FormsAuthentication.FormsCookiePath;

                HttpContext.Current.Response.Cookies.Set(AuthCookie);
            }
            CurrentUser = GetById(UserId);
            return LoginState.success;
        }
        /// <summary>
        /// 验证用户名及密码，根据数据库
        /// </summary>
        /// <param name="userName">用户帐号</param>
        /// <param name="password">用户登陆密码</param>
        /// <param name="loginIP">用户当前登陆IP</param>
        /// <returns></returns>
        private static LoginState IsAuthenticated(string userName, string pwd, string loginIP,ref int UserId)
        {
            try
            {
                OUserInfo objNews = CBO.FillObject<OUserInfo>(OUserDAL.UserLogin(userName, StringHelper.GetPwdEncrypt(pwd), loginIP));
                UserId = objNews.UserId;
                if (objNews == null)
                {
                    return LoginState.inputerror;
                }
                else if (objNews.State == 1)
                {
                    return LoginState.other;
                }
                else
                {
                    return LoginState.success;
                }
            }
            catch
            {
                UserId = 0;
                return LoginState.other;
            }
            finally
            {

            }
        }
        /// <summary>
        /// 获取或设置当前使用用户
        /// </summary>
        public static OUserInfo CurrentUser
        {
            get
            {
                try
                {
                    int UserId = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
                    OUserInfo obj=DC.Get<OUserInfo>(GetDataCacheKey(LoginOUserInfo,UserId));
                    if(obj ==null)
                    {
                        obj=GetById(UserId);
                        DC.Add(GetDataCacheKey(LoginOUserInfo, UserId),obj);
                    }
                    return obj;
                }
                catch
                {
                    return new OUserInfo();
                }
            }
            set
            {
                //处理缓存
                DC.Remove(GetDataCacheKey(LoginOUserInfo,value.UserId));
                DC.Add(GetDataCacheKey(LoginOUserInfo, value.UserId), value);
                
            }
        }
        /// <summary>
        /// 退出系统
        /// </summary>
        /// <returns></returns>
        public static bool LoginOut()
        {
            DC.Remove(GetDataCacheKey(LoginOUserInfo, CurrentUser.UserId));

            FormsAuthentication.SignOut();

            System.Web.HttpContext.Current.Session.Abandon();

            return true;
        }
        #endregion

        public static bool Add(OUserInfo obj)
        {
            obj.PassWord = StringHelper.GetPwdEncrypt(obj.PassWord);
            return OUserDAL.Add(obj);
        }
        public static bool CheckUserName(string UserName)
        {
            return OUserDAL.CheckUserName(UserName);
        }
        public static bool Delete(int UserId)
        {
            return OUserDAL.Delete(UserId);
        }
        public static OUserInfo GetById(int UserId)
        {
            return CBO.FillObject<OUserInfo>( OUserDAL.GetById(UserId));
        }
        public static OUserInfo GetByUserName(string UserName)
        {
            OUserInfo obj= CBO.FillObject<OUserInfo>(OUserDAL.GetByUserName(UserName));
            if (obj == null)
                return new OUserInfo();
            return obj;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="RealName"></param>
        /// <param name="RoleId">角色ID</param>
        /// <param name="UserType"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Sort"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public static DataTable GetPagination(string RealName, string RoleId, int UserType, int PageIndex, int PageSize, string Sort, ref int TotalCount)
        {
            return OUserDAL.GetPagination(RealName,RoleId, UserType, PageIndex, PageSize, Sort, ref  TotalCount);
        }

        public static bool Update(OUserInfo obj)
        {
            return OUserDAL.Update(obj);
        }
          /// <summary>
        /// 用户登陆后更改密码或给用户重置密码
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="PassWord"></param>
        /// <returns></returns>
        public static bool EditPwd(int UserId, string PassWord)
        {
            return OUserDAL.EditPwd(UserId, PassWord);
        }

        /// <summary>
        /// 更改用户状态
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="State">0表示启用,1表示禁用</param>
        /// <returns></returns>
        public static bool ChangeState(int UserId, int State)
        {
            return OUserDAL.ChangeState(UserId, State);
        }

        public static void UpdateLastLogin(int UserId, string lastIp)
        {
            OUserDAL.UpdateLastLogin(UserId, lastIp);
        }

         /// <summary>
        /// 更新个性化设置
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="MySetting"></param>
        /// <returns></returns>
        public static bool ChangeMySetting(int UserId, string MySetting)
        {
            DC.Remove(GetDataCacheKey(LoginOUserInfo, UserId));
            return OUserDAL.ChangeMySetting(UserId, MySetting);
        }
    }
}

